/*
 * build_tree.cpp
 *
 *  Created on: Sep 25, 2012
 *      Author: pickrell
 */
#include "TreeState.h"
#include "CmdLine.h"
using namespace std;

string infile;
string outstem = "tree";


void printopts(){
	cout << "\nbuild_tree v. 0.0\n";

	cout << "Options:\n";
	cout << "-i [file name] input file\n";
	cout << "-o [stem] output stem (will be [stem].treeout.gz, [stem].cov.gz, [stem].modelcov.gz)\n";


	cout << "\n";
}

bool upgma = false;
int main(int argc, char *argv[]){

	const gsl_rng_type * T;
	gsl_rng * r;
	gsl_rng_env_setup();
	T = gsl_rng_ranlxs2;
	r = gsl_rng_alloc(T);
	int seed = (int) time(0);
	gsl_rng_set(r, seed);

    CCmdLine cmdline;
    PhyloPop_params p;
    if (cmdline.SplitLine(argc, argv) < 1){
    	printopts();
    	exit(1);
    }
    if (cmdline.HasSwitch("-i")) infile = cmdline.GetArgument("-i", 0).c_str();
    else{
    	printopts();
    	exit(1);
    }
    if (cmdline.HasSwitch("-o")) outstem = cmdline.GetArgument("-o", 0);
    if (cmdline.HasSwitch("-upgma")) upgma  = true;
    Alignment aln(infile);
    TreeState ts(&aln, &p);

    if (upgma) ts.set_UPGMA();
    else{
    	while (aln.nchrom > ts.current_nhap){
    		ts.add_pop();
    		ts.iterate_hillclimb();
    		cout << "llk: "<< ts.tree->current_llk << "\n";
    	}
    	ts.tree->set_edge_lens();
    }
    string outnewick = outstem+".treeout.gz";
    ogzstream out(outnewick.c_str());
    out << ts.tree->get_newick_format() << "\n";
    ts.tree->print(outstem);
    return 0;
}

